package server.start;

import com.alibaba.dubbo.config.ProtocolConfig;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import util.AppConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class ServiceServer {

	private static final Logger log=Logger.getLogger(ServiceServer.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		long begin=System.currentTimeMillis();
		try{
			final ApplicationContext context=initSpringContext();
			//SchedulerHelper.dynamicStartTrigger(context);
//			addShutdownHook(context);
		}catch (Throwable t){
			log.error("服务启动时发生异常: ",t);
			System.exit(0);
		}
		log.warn("服务启动完毕,共耗时 "+(System.currentTimeMillis()-begin)+"毫秒，本服务仅供服务器间内部调用。");
		for(;;){
			try {
//				TimeUnit.MINUTES.sleep(5);
//				ProfileStatHolder.printPerformanceLog("Service.");
			} catch (Exception e) {
				log.error("打印日志失败",e);
			}
		}
	}

	public static ApplicationContext initSpringContext() {
		// Configure the server.
		List<String> config=new ArrayList<String>();
//		config.add("/applicationContext-server.xml");
//		config.add("/applicationContext-batch-import.xml");
//		config.add("/custom/applicationContext-custom-"+GudongConfig.PLATFORM_TYPE+".xml");
		config.add("/applicationContext-server.xml");
//		config.add("/applicationContext-special.xml");
		if(AppConfig.NEED_SCHEDULE){
			config.add("/applicationContext-schedule.xml");
		}
		final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config.toArray(new String[0]));
		context.registerShutdownHook();//非web应用的环境下使用Spring的IoC容器，让容器优雅的关闭，并调用singleton bean上的相应析构回调方法 @PreDestroy
		context.start();
		return context;
	}

	protected static void addShutdownHook(final ApplicationContext context) {
		Runtime.getRuntime().addShutdownHook(new Thread("Stop Servers") {
			public void run() {
				// 将在线的 SessionInfo 改为离线状态
//		    	ISessionService sessionService=(ISessionService)context.getBean("sessionService");
//		    	sessionService.resetAllSessions();
				//优雅关闭dubbo
				ProtocolConfig.destroyAll();
				if (log.isInfoEnabled()) {
					log.warn("Service Server stopped successful");
				}
			}
		});
	}
}
